import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Layout from './Layout';
import route from './route';

import './App.css';

const App = () => {
  return (
    <Router>
      <Suspense fallback={<div>Loading application...</div>}>
        <Routes>
          {route.map((item) => {
            const { layout = true, path, component } = item;
            const LazyComponent = lazy(() => import(`${component}`).catch(err => {
              console.error(`Error loading component ${component}: `, err);
              return () => <div>Component load error: {component}</div>;
            }));

            if (layout) {
              return (
                <Route
                  key={path}
                  path={path}
                  element={
                    <Suspense fallback={<div>Loading layout...</div>}>
                      <Layout>
                        <Suspense fallback={<div>Loading component...</div>}>
                          <LazyComponent />
                        </Suspense>
                      </Layout>
                    </Suspense>
                  }
                />
              );
            }
            return (
              <Route
                key={path}
                path={path}
                element={
                  <Suspense fallback={<div>Loading component...</div>}>
                    <LazyComponent />
                  </Suspense>
                }
              />
            );
          })}
        </Routes>
      </Suspense>
    </Router>
  );
};

export default App;
